var myDate = new Date();
$(function(){
  var startDate=null;
  var endDate=null;
  $("#start").click(function(){
    if($("#end").val()!=""){
      endDate="'"+$("#end").val()+"'";
    }
    $('#start').datepicker('setEndDate', endDate);
  });
  //当$("#end")的值不为空时$("#start")的endDate为$("#end")的值
  $("#end").click(function(){
    if($("#start").val()!=""){
      startDate="'"+$("#start").val()+"'";
    }
    //console.log(startDate);
    $('#end').datepicker('setStartDate', startDate);
  });

  $("#start").datepicker({
    autoclose: true,
    format: 'yyyy-mm-dd',
    orientation : 'top',
    todayHighlight:true
  });

  $("#end").datepicker({
    autoclose: true,
    format: 'yyyy-mm-dd',
    orientation : 'top',
    todayHighlight:true
  });


  $('#start').val(myDate.getFullYear()-1+'-'+(myDate.getMonth()+1)+'-'+1);
  $('#end').val(myDate.getFullYear()+'-'+(myDate.getMonth()+1)+'-'+myDate.getDate());
});

//表格
$(function() {
  $.jgrid.defaults.styleUI = "Bootstrap";

  $("#table_list").jqGrid({


    datatype: "json",                                              //请求的数据类型
    mtype: "POST",                                                  //请求类型
    height: 330,                                                   //设置高度
    autowidth: true,                                               //自动匹配宽度
    shrinkToFit: true,
    rowNum: 10,                                                    //每页显示记录数
    rowList: [10, 20, 30],                                       //分页选项，可以下拉选择每页显示记录数
    colNames: ["id","用户类型", "账号","姓名","密码", "生日", "入学时间", "手机", "邮箱","专业"],                //数据列名称（数组）
    //数据列各参数信息设置
    colModel: [{name: "id", index: "id", width: 20},
      {name: "userTypeTo", index: "usertype", width: 30,editable:true,edittype:'select',editoptions:{value:gettypes()}},
      {name: "username", index: "username", width: 30,editable:true,editrules:{custom:true,required:true, custom_func:checkValidate}},
      {name: "realname", index: "realname", width: 30,editable:true,editrules:{custom:true,required:true, custom_func:checkRealName}},
      {name: "password", index: "password", width: 30,edittype:'password',sortable:false,editable:true,editrules:{custom:true, custom_func:checkpwd}},
      {name: "birthdayTo", index: "birthday", width: 25,editable:true,edittype:'data'},
      {name: "intimeTo", index: "intime", width: 25,editable:true,},
      {name: "phone", index: "phone", width: 30,editable:true,editrules:{custom:true, custom_func:checkPhone}},
      {name: "email", index: "email", width: 35,editable:true,editrules:{custom:true, custom_func:checkMail}},
      {name: "majorid", index: "majorid", width: 20,editable:true,edittype:'select',editoptions:{value:getmajor()},formatter:majora},

    ],
    pager: "#pager_list",                                         //表格数据关联的分页条，html元素
    viewrecords: true,                                            //显示总记录数
    //这是一个数组，用于设置jqGrid将要向Server传递的参数名称
    jsonReader: {
      id: "id",                                           //相当于设置主键
      root: "dataList",                                        //Json数据
      records: "record",                                      //总记录数
      repeatitems: false
    },
    multiselectWidth: 25,                                          //设置多选列宽度
    multiselect: false,                                            //可多选，出现多选框
    gridview: true,                                                 //加速显示
    sortable: true,                                                //可以排序
    sortname: 'id',
    sortorder: "asc",                                //可以排序
    hidegrid: false,
    toppager: true ,                                               //同步导航栏至表格顶部


  });


  /*********************************
   功能：初始化导航栏
   *********************************/
  $("#table_list").jqGrid("navGrid", "#pager_list", {

        edit : true,
        add : true,
        del : true,
        search : false,
        view: true,
        cloneToTop:true
      }, {
        editCaption : "编辑",
        closeOnEscape:true,      //是否可以使用esc键关闭对话框
        closeAfterEdit:true,     //在添加模式下，保存添加的记录后关闭对话框
        modal:true,
        top:20,
        left:250,
        width:420,
        //height : 430,
        drag:false,               //设置对话框是否可以拖拽。
        url:$(path).val()+'/UserUpdate2',
        editData:{
          password:function(){
            var pwd=$("#password").val();
            if(pwd=="******")
              return "";
            return $.md5(pwd);
          }
        },
        reloadAfterSubmit : true,
        closeOnEscape:true,
        beforeShowForm:function(frm){
          frm.find('#userTypeTo').attr("disabled","disabled");//只读的。
          frm.find('#username').attr('readOnly',true);
          frm.find('#majorid').attr('readOnly',true);
          frm.find('#birthdayTo').datepicker({
            autoclose: true,
            format: 'yyyy-mm-dd',
            orientation : 'top',
            todayHighlight:true
          });
          frm.find('#intimeTo').datepicker({
            autoclose: true,
            format: 'yyyy-mm-dd',
            orientation : 'top',
            todayHighlight:true
          });
        },
        afterSubmit : function(response, postdata) {
          var json = response.responseText;
          var result =$.parseJSON(json);
          if (result.status=='true') {
            swal(result.msg,"","success");
          }else{
            swal(result.msg,"","warning");
          }
          return [result.status, result.msg, ""];
        }
      },
      {
        addCaption: "添加",
        closeOnEscape:true,     //是否可以使用esc键关闭对话框
        closeAfterAdd:true,     //在添加模式下，保存添加的记录后关闭对话框
        modal:true,
        top:20,
        left:250,
        width:420,
        //height : 430,
        drag:false,               //设置对话框是否可以拖拽。
        url:$(path).val()+'/addUser',
        editData:{
          password:function(){
            var pwd=$("#password").val();
            return $.md5(pwd);
          },
          usertype:function(){
            return $("#userTypeTo").val();
          },
          id:0,
        },
        reloadAfterSubmit : true,
        onInitializeForm : function(frm) {
          frm.find('#realname').attr("autocomplete","off")
          frm.find('#password').attr("autocomplete","off")
          frm.find('#majorid').val(1).attr('readOnly',true);
          frm.find('#birthdayTo').datepicker({
            autoclose: true,
            format: 'yyyy-mm-dd',
            orientation : 'top',
            todayHighlight:true,
          });
          frm.find('#intimeTo').datepicker({
            autoclose: true,
            format: 'yyyy-mm-dd',
            orientation : 'top',
            todayHighlight:true,
          });
        },
        afterSubmit : function(response, postdata) {
          var json = response. responseText;
          var result =$.parseJSON(json);
          if (result.status=='true') {
            swal(result.msg,"","success");
          }else{
            swal(result.msg,"","warning");
          }

          return [result.status, result.msg, ""];
        }
      },
      {
        delCaption: "删除",
        top:120,
        left:400,
        drag:false,               //设置对话框是否可以拖拽。
        reloadAfterSubmit : true ,
        modal:true,
        url:$(path).val()+'/deleteUser',
        afterSubmit : function(response, postdata) {
          var json = response.responseText;
          var result =$.parseJSON(json);
          if (result.status=='true') {
            swal(result.msg,"","success");
          }else{
            swal(result.msg,"","warning");
          }
          return [result.status, result.msg, ""];
        }
      },
      {},
      {
        viewCaption: "查看详情",
        drag:false,               //设置对话框是否可以拖拽。
        top:20,
        left:250,
        width:420,
        modal:true,

      }
  );


  /*********************************
   功能：隐藏底部的导行栏
   *********************************/
  $('#table_list_toppager_center').hide();   //隐藏底部的导行栏



  $(window).bind("resize", function () {
    var width = $(".jqGrid_wrapper").width();
    $("#table_list").setGridWidth(width);
  });



  $("#queryButton").click(function () {
    var name = $("#name").val();
    var start = $("#start").val();
    var end = $("#end").val();
    if(end==""||start==""){
      if(end=="")
      {
        end=start;
      }
      else if( start=="")
      {
        start=end;
      }
    }
    if(end!=""&&start!=""){
      start+=" 00:00:00";
      end+=" 23:59:59";
    }

    $("#table_list").jqGrid('setGridParam', {
      url: $(path).val() + '/getAllUser',
      dataType: 'json',
      postData: {
        name: name,
        start: start,
        end: end,
        flag: "role",
      },
      page: 1
    }).trigger('reloadGrid'); //重新载入
  });

  function start(cellValue){
  if(cellValue=="0") return "启用";
    else return "未启用";
  }





});

function gettypes(){
  return "1:管理员;2:专业负责人;3:校友"
}
function getmajor(){
  return "1:计算机专业"
}
function majora(cellval){
if(cellval==1){
  return  "计算机专业";
}
}


//  只能  数字字母
function checkValidate(str){
  var reg = /^[A-Za-z0-9]+$/;
  if(reg.test(str)&&str.length<11&&str.length>5){
    return [true,""];
  }
  else
    return [false,"6~12字符且只能数字,字母"];
}

function checkRealName(str){
  if(str.length<11){
    return [true,""];
  }
  else
    return [false,"不能超过10个字符"];
}

function checkpwd(value, colname){
  if (value!=null&&value!=""&&value.length>5&&value.length<13)
    return [true,""];
  else
  return [false,"密码要在6~12位"];
}
function checkPhone(o){
  var reg=/^0{0,1}(13[4-9]|15[7-9]|15[0-2]|18[7-8])[0-9]{8}$/;
  if(reg.test(o)){
    return [true,""];
  }
  else
    return [false,"手机号码错误"];
}

function checkMail(o){
  var reg=/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  if(reg.test(o)){
    return [true,""];
  }
  else
    return [false,"邮箱格式错误"];
}

function changeStart(e,id,name,start){
  var flag;
  if(start=="true"){
    $(e).text("关闭中...").attr("disabled","true").removeClass("btn-red");
    flag=false;
  }
  else{
    $(e).text("启动中...").attr("disabled","true").removeClass("btn-success");
    flag=true;
  }
  $.get($(path).val() + "/Config/updateQuestionnaireConfig?"+name+"="+flag+"&id="+id+"&title="+name,
      function(json){
          var result=JSON.parse(json);
        $(e).text(result.msg)
        if(result.status=="success"){
        if(start=="true"){
          $(e).text("状态(关闭)-->启用").removeAttr("disabled").addClass("btn-success").val(flag);
        }
        else{
          $(e).text("状态(启用)-->关闭").removeAttr("disabled").addClass("btn-red").val(flag);
        }

        }
        else{
          if(start!="true"){
            $(e).text("状态(关闭)-->启用").removeAttr("disabled").addClass("btn-success");
          }
          else{
            $(e).text("状态(启用)-->关闭").removeAttr("disabled").addClass("btn-red");
          }
        }
      }
  );
}